package it.fuesi.myseries.activities;

import it.fuesi.myseries.R;
import it.fuesi.myseries.api.ApiBrokerService;
import it.fuesi.myseries.api.ApiMethod;
import it.fuesi.myseries.model.MySeriesConstant;
import it.fuesi.myseries.model.Serie;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.image.SmartImageView;

public class SerieDetailActivity extends Activity implements Observer {

	private Serie currentSerie;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_serie_detail);

		final TextView nameText = (TextView) findViewById(R.id.name);
		final TextView ovewViewText = (TextView) findViewById(R.id.overview);
		final SmartImageView imageView = (SmartImageView) findViewById(R.id.banner);

		final Button add = (Button)findViewById(R.id.add);
		add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addToMySeries();
				
			}
		});
		
		final Intent intent = getIntent();
		currentSerie = (Serie) intent.getSerializableExtra("EXTRA_MESSAGE");

		nameText.setText(currentSerie.getName());
		ovewViewText.setText(currentSerie.getOverview());

		imageView.setImageUrl(currentSerie.getBanner());

	}

	private void addToMySeries(){
		
		Intent intent = ApiBrokerService.getApiTaskIntent(this, ApiMethod.putSerie);
		
		intent.putExtra(MySeriesConstant.ID.toString(), currentSerie.getId());

		startService(intent);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.serie_detail, menu);
		return true;
	}
	
	@Override
	public void update(Observable observable, Object results) {
		final Bundle bundle = (Bundle) results;

		final boolean success = bundle.getBoolean(MySeriesConstant.SUCCESS.toString());
		final String error = bundle.getString(MySeriesConstant.ERROR.toString());
		
		final String msg;
		
		if(success)
			msg = "Added " + currentSerie.getName() + " to my series";
		else
			msg = "Fail adding " + currentSerie.getName() + " to my series: " + error;
		
		Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
		
		if(success)
			this.finish();
		
	}

}
